#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@File    :   function_utils.py    
@Contact :   pengwei.sun@aihuishou.com
@License :   (C)Copyright aihuishou

@Modify Time      @Author       @Version    @Desciption
------------      -----------   --------    -----------
2021-08-02 10:53   pengwei.sun      1.0         None
'''
import os
import datetime
import pickle
import numpy as np
import pandas as pd
from src.utils.config import logger

def save_pickle_data(file,data_df):

    train_data = open(file, 'wb')
    pickle.dump(data_df, train_data)
    train_data.close()
    logger.info('save pickle data!')

def load_pickle_data(file):
    train_data = open(file, 'rb')
    resDf = pickle.load(train_data)
    logger.info('load pickle data!')
    return resDf

def combine_rank_min_max_price(df,target):

    result_t=target[['product_sku_key','product_level_key','template_rank','process_price']].copy()
    sku_rank_price = result_t.groupby(by=['product_sku_key','template_rank'])['process_price'].agg({'rank_price_max':'max','rank_price_min':'min'}).reset_index()
    sku_rank_price['row_rank']=sku_rank_price['template_rank'].groupby(sku_rank_price['product_sku_key']).rank(ascending=True, method='first')

    result_t[['product_sku_key','product_level_key', 'template_rank']]=result_t[['product_sku_key','product_level_key', 'template_rank']].apply(
        np.int64)
    df[['product_sku_key', 'template_rank']] = df[['product_sku_key', 'template_rank']].apply(
        np.int64)
    # 价格段的数据合并到数据中

    sku_rank_price['ceil_rank']= sku_rank_price['row_rank']+1
    sku_rank_price['floor_rank']= sku_rank_price['row_rank']-1
    result = result_t.merge(sku_rank_price[['product_sku_key','template_rank','row_rank']], how='left', on=['product_sku_key','template_rank'])

    result = result.merge(sku_rank_price[['product_sku_key','floor_rank','rank_price_max']], how='left', left_on=['product_sku_key','row_rank'],right_on=['product_sku_key','floor_rank'])
    result = result.merge(sku_rank_price[['product_sku_key','ceil_rank','rank_price_min']], how='left', left_on=['product_sku_key','row_rank'],right_on=['product_sku_key','ceil_rank'])
    df=df.drop(['rank_price_max','rank_price_min'], axis=1)

    result[['product_sku_key', 'product_level_key']] = result[['product_sku_key', 'product_level_key']].apply(np.int64)
    df[['product_sku_key', 'product_level_key']] = df[['product_sku_key', 'product_level_key']].apply(np.int64)
    try:
        res=df.merge(result[['product_sku_key', 'product_level_key','rank_price_max','rank_price_min']],how='left',on=['product_sku_key', 'product_level_key'])
        # return res
    except Exception as e:
        logger.info('Exception')
        raise TypeError('sku2 combine_rank_min_max_price处理失败:') from e
    return res


def inverse_rate_fun(result_t):
    # result_t = result_t.loc[result_t.product_sku_key==2670304]
    result_t=result_t.loc[result_t.level_sub.isin(['S','A','B','C','D','E'])]
    resDf = pd.DataFrame(columns=result_t.columns.tolist())
    grouped = result_t.groupby('product_sku_key')
    for name, group in grouped:
        group.reset_index(drop=True, inplace=True)
        group = group.sort_values('template_rank', ascending=True)
        group['product_level_name_tmp']=group['product_level_name']
        group['rank_tmp'] = group['rank']
        group['saleprice_tmp'] = group['saleprice']

        size = group.shape[0]
        if size<=2:
            continue
        result_t = group

        for index in range(size):

            iter_size = 0
            iter_size_bi = 0
            iverse = 0
            iverse_bi = 0
            if result_t.loc[index,'level_sub'] in ['S','A','B','C','D'] and index+1<=size and  result_t.loc[index,'product_level_name']:
                for i in range(index+1,size,1):
                    if result_t.loc[index, 'template_rank']==result_t.loc[i, 'template_rank'] :
                        continue
                    iter_size+=1
                    iter_size_bi+=1
                    if result_t.loc[index, 'process_price']<result_t.loc[i, 'process_price'] and result_t.loc[index, 'template_rank']<result_t.loc[i, 'template_rank']:
                        iverse_bi=iverse_bi+1
                        result_t.loc[i, 'weight_cnt']=result_t.loc[i, 'weight_cnt']+1
                        result_t.loc[index, 'weight_cnt']=result_t.loc[index, 'weight_cnt']+1

                    if result_t.loc[index, 'saleprice']<result_t.loc[i, 'saleprice'] and result_t.loc[index, 'template_rank']<result_t.loc[i, 'template_rank']:
                        iverse=iverse+1

                result_t.loc[index, 'iter_size']=iter_size
                result_t.loc[index, 'iter_size_bi']=iter_size_bi
                result_t.loc[index, 'iverse']=iverse
                result_t.loc[index, 'iverse_bi']=iverse_bi
            # print(' .')
        resDf = resDf.append(result_t.copy())
    return resDf


def check_conflict_file(directory, file_name, file_suffix=None, is_remove_old_file=False):
    """
    1. 检查目录是否存在，不存在时创建新目录
    2. 检查文件是否存在，如果存在则将文件重命名
    :param directory: 路径
    :param file_name: 文件名
    :param file_suffix: 文件存在时，给文件增加后缀名，如果为None，则设定为当前时间
    :param is_remove_old_file: 是否删除旧文件
    :return:
    """
    if not os.path.exists(directory):
        logger.info('make new directory@{}'.format(directory))
        os.makedirs(directory, exist_ok=True)

    checking_file = os.path.join(directory, file_name)
    if os.path.exists(checking_file):
        if is_remove_old_file:
            os.remove(checking_file)
            logger.info('remove {}'.format(checking_file))
        else:
            if file_suffix is None:
                file_suffix = datetime.datetime.now().strftime('%Y-%m-%d_%H-%M-%S')
            new_file_name = os.path.join(directory, file_name + '.' + file_suffix)
            logger.info('rename {} to {}'.format(checking_file, new_file_name))
            os.rename(checking_file, new_file_name)